package com.atguigu.day01;

import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author Felix
 * @date 2024/7/08
 * 以流的形式对有界数据进行处理
 */
public class Flink02_WC_bound_stream {
    public static void main(String[] args) {
        //TODO 1.指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //指定以批的形式对数据进行处理
        env.setRuntimeMode(RuntimeExecutionMode.BATCH);

        //TODO 2.从指定的文件中读取数据
        DataStreamSource<String> ds = env.readTextFile("D:\\dev\\workspace\\bigdata-0221\\input\\wc.txt");
        //TODO 3.对读取的数据进行扁平化处理  封装为二元组
        SingleOutputStreamOperator<Tuple2<String, Long>> flatMapDS = ds.flatMap(
                new FlatMapFunction<String, Tuple2<String, Long>>() {
                    @Override
                    public void flatMap(String lineStr, Collector<Tuple2<String, Long>> out) throws Exception {
                        //对读取的一行数据进行切分
                        String[] wordArr = lineStr.split(" ");
                        for (String word : wordArr) {
                            //将单词封装为二元组 向下游传递
                            out.collect(Tuple2.of(word, 1L));
                        }
                    }
                }
        );
        //TODO 4.按照单词进行分组
        KeyedStream<Tuple2<String, Long>, Tuple> keyedDS = flatMapDS.keyBy(0);
        //TODO 5.计数
        SingleOutputStreamOperator<Tuple2<String, Long>> sumDS = keyedDS.sum(1);
        //TODO 6.打印输出
        sumDS.print();
        //TODO 7.提交作业   注意：如果是DataStreamAPI，需要手动的提交作业
        try {
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
